package org.example.chat_room.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.example.chat_room.component.OnlineUserManager;
import org.example.chat_room.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ssl.SslAutoConfiguration;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private MessageSessionMapper messageSessionMapper;

    @Resource
    private MessageMapper messageMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[WebSocketAPI] 连接建立完成！");
        User user = (User) session.getAttributes().get("user");
        if (user == null){
            return;
        }
//        上线，将session存储键值对
        onlineUserManager.online(user.getUserId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[WebSocketAPI] 收到消息!" + message.toString());
        User user = (User) session.getAttributes().get("user");
        if (user == null){
            System.out.println("[WebSocketAPI]用户不存在！无法进行消息转发");
            return;
        }
//        要将接收到的请求进行解析，将json格式的字符串转换为Java中的对象
        MessageRequest req = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if (req.getType().equals("message")){
            transferMessage(user,req);
        } else{
            System.out.println("[WebSocketAPI] rep.type:" + req.getType()+"不符合要求");
        }
    }

//    实现消息的转发，构造响应数据,根据sessionId找到这个messageS饿死送有哪些用户，遍历列表，给列表的用户都发一份响应消息
    private void transferMessage(User fromUser, MessageRequest req) throws IOException {
        MessageResponse messageResponse = new MessageResponse();
        messageResponse.setFromId(fromUser.getUserId());
        messageResponse.setFromName(fromUser.getUsername());
        messageResponse.setSessionId(req.getSessionId());
        messageResponse.setContent(req.getContent());
//        要将Java对象转换为json数组
        String respJson = objectMapper.writeValueAsString(messageResponse);
        System.out.println("[transferMessage] respJson"+respJson);

        List<Friend> friends = messageSessionMapper.getFriendsBySessionId(req.getSessionId(), fromUser.getUserId());
        Friend myself = new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);

        for (Friend friend : friends){
            WebSocketSession webSocketSession = onlineUserManager.getSession(friend.getFriendId());
            if (webSocketSession == null){
//                用户不在线则不发送消息
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respJson));
        }
//        转发的消息需要记录到数据库
        Message message = new Message();
        message.setFromId(fromUser.getUserId());
//        message.setFromName(fromUser.getUsername());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());
        messageMapper.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("[WebSocketAPI] 连接异常!" + exception.toString());
        User user = (User) session.getAttributes().get("user");
        if (user == null){
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("[WebSocketAPI] 连接关闭!" + status.toString());
        User user = (User) session.getAttributes().get("user");
        if (user == null){
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }
}
